<template>
  <div class="message-container" ref="messageContainer">
    <MessageArea title="留言板" :subtitle="`(${data.total})`" :list="data.rows" :isListLoading = "isLoading" @submit="handleSubmit"/>
    <Empty v-if="data.rows.length === 0 && !isLoading" />
  </div>
</template>

<script>
import MessageArea from "@/components/MessageArea";
import fetchData from "@/mixins/fetchData.js";
import * as msgApi from '@/api/message.js';
import setScroll from '@/mixins/setScroll.js';
import Empty from '@/components/Empty';
export default {
  mixins: [fetchData({ total: 0, rows: [] }),setScroll('messageContainer')],
  components: {
    MessageArea,
    Empty,
  },
  data(){
    return {
      page:1,
      limit:10,
    }
  },
  created() {
    this.$bus.$on("mainScroll", this.handleScroll);
  },
  destroyed(){
    this.$bus.$off("mainScroll",this.handleScroll);
  },
  computed: {
    hasMore() {
      return this.data.rows.length < this.data.total;
    },
  },
  methods:{
    async fetchData(){
      return await msgApi.getMessages(this.page,this.limit);
    },
    async handleSubmit(data,callback){
      const resp = await msgApi.postMessage(data);
      callback('Nice advice!');
      this.data.rows.unshift(resp);
    },
    handleScroll(dom) {
      if(this.isLoading || !dom){
        //如果正在加载中
        return;
      }
      //区间范围
      const range = 100;
      const desc = Math.abs(
        dom.scrollTop + dom.clientHeight - dom.scrollHeight
      );
      if (desc <= range) {
        //到达底部
        this.fetchMore();
      }
    },
    async fetchMore() {
      if (!this.hasMore) {
        //没有更多了
        return;
      }
      this.isLoading = true;
      this.page++;
      const resp = await this.fetchData();
      this.data.total = resp.total;
      this.data.rows = this.data.rows.concat(resp.rows);
      this.isLoading = false;
    },
  }
};
</script>

<style scoped lang="less">
.message-container {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  overflow-y: auto;
  padding: 25px 0;
  scroll-behavior: smooth;
}
.message-area-container {
  width: 700px;
  margin: 0 auto;
}
</style>